<template>
  <div class="my-tag">
    <input
      class="input"
      type="text"
      placeholder="输入标签"
      v-if="flag"
      v-model.trim="str"
      v-select
      ref="myInput"
      @input="widthInput($event)"
      @blur="blurInput"
      @keyup.enter="blurInput"
    />
    <div class="text" v-else @dblclick="InputFlag">{{ value }}</div>
  </div>
</template>

<script>
export default {
  props: {
    value: {
      type: [Number, String],
      required: true,
      default: () => '',
    },
  },
  data() {
    return {
      flag: false,
      str: '',
    }
  },
  methods: {
    // 双击事件，使input框显示
    InputFlag() {
      this.flag = true
      this.str = this.value
      // 根据内容获取input框长度
      this.$nextTick(() => {
        console.log(this.$refs.myInput.style.width);
        // this.$refs.myInput.style.width = this.$refs.myInput.value.length * 20 + 'px'
      })
    },
    // 失焦事件
    blurInput() {
      this.flag = false
      if (this.str === '') {
        this.str = this.value
        alert('值不能为空')
      } else {
        this.$emit('input', this.str)
      }
    },
    // input事件，输入框输入时，控制宽度
    widthInput(e) {
      this.$nextTick(() => {
        console.log(e.target.style.width);
        // e.target.style.width = e.target.value.length * 20 + 'px'
      })
      // e.style.width = (e.target.value.length * 10 + 'px')
    },
  },
}
</script>

<style lang="less" scoped>
.my-tag {
  cursor: pointer;
  .input {
    appearance: none;
    outline: none;
    border: 1px solid #ccc;
    min-width: 100px;
    max-width: 300px;
    // width: 100px;
    height: 40px;
    box-sizing: border-box;
    padding: 10px;
    color: #666;
    &::placeholder {
      color: #666;
    }
  }
}
</style>
